package com.ph.shopping.facade.merchant.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.ph.shopping.common.core.base.BaseService;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.customenum.TransCodeEnum;
import com.ph.shopping.common.core.exception.BizException;
import com.ph.shopping.common.util.com.order.Constants;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.facade.mapper.MerchantMapper;
import com.ph.shopping.facade.mapper.UserBalanceMapper;
import com.ph.shopping.facade.merchant.entity.UserBalance;
import com.ph.shopping.facade.merchant.entity.UserBalanceRecord;
import com.ph.shopping.facade.merchant.service.IMerchantService;
import com.ph.shopping.facade.merchant.service.IUserBalance;

import cm.ph.shopping.facade.order.entity.PhAgentOrder;
import cm.ph.shopping.facade.order.entity.PhMerchantOrder;
import cm.ph.shopping.facade.order.entity.PhOrderUnline;
import cm.ph.shopping.facade.order.service.IAgentOrderService;
import cm.ph.shopping.facade.order.service.IManagerOrderService;
import cm.ph.shopping.facade.order.service.IMerchantOrderService;
import cm.ph.shopping.facade.order.service.IUnLineOrerService;

@Component
@Service(version="1.0.0")
@Transactional
public class UserBalanceImpl extends BaseService implements IUserBalance {

	@Autowired
	private MerchantMapper merchantMapper;
	
	@Autowired
	private UserBalanceMapper userBalanceMapper;
	
	@Reference(version="1.0.0")
	IAgentOrderService  iAgentOrderService;
	
	@Reference(version="1.0.0")
	IMerchantOrderService  iMerchantOrderService;
	
	@Reference(version="1.0.0")
	IUnLineOrerService  iUnLineOrerService;
	/**
	 * 
	* Title: userBalanceTrade
	* Description:用户余额交易
	* 来调用此方法前先将消费金额 * 10000 
	* @author WQiang
	* @date 2017年3月29日 下午5:55:01
	* @param memberId
	* @param codeEnum
	* @param type
	* @param money
	* @return 
	* @see com.ph.shopping.facade.merchant.service.IUserBalance#userBalanceTrade(long, com.ph.shopping.common.core.customenum.TransCodeEnum, int, long)
	 */
	@Override
	@Transactional(rollbackFor=BizException.class)
	public int userBalanceTrade(Long memberId, TransCodeEnum codeEnum, int type, Long money,Long orderId,String orderNo) throws Exception {
		String orderNo1 ="";//订单号
		money = codeEnum.getMark() * money;
		if(String.valueOf(codeEnum.getCode()).equals("1006")){
			PhAgentOrder p = new PhAgentOrder();
			p.setId(orderId);
			p.setStatus(2);
			int updateForOrderStatus = iAgentOrderService.updateForOrderStatus(p);
			if(updateForOrderStatus !=1){
				throw new Exception("更新供应链代理支付失败");
			}
			orderNo = iAgentOrderService.findAgentOrderByTarget(p).getOrderNo();
		}
		if(String.valueOf(codeEnum.getCode()).equals("1007")){
			PhMerchantOrder p = new PhMerchantOrder();
			p.setId(orderId);
			p.setStatus(2);
			int updateForOrderStatus = iMerchantOrderService.updateForOrderStatus(p);
			if(updateForOrderStatus !=1){
				throw new Exception("更新供应链商户支付失败");
			}
			orderNo = iMerchantOrderService.findMerchantOrderByTarget(p).getOrderNo();
		}
		
		if(String.valueOf(codeEnum.getCode()).equals("1013")){//商户提现
			//更改用户提现记录表中的状态
			userBalanceMapper.updateMerchantWithdrawals(orderNo, 2);//提现成功
			//更改分润表中关于提现的审核的状态
			userBalanceMapper.updateUserBalanceStatus(orderNo, 2);//审核通过
		}
		
		if(String.valueOf(codeEnum.getCode()).equals("1014")){//代理提现
			//更改用户提现记录表中的状态
			userBalanceMapper.updateAgentWithdrawals(orderNo, 2);//提现成功
			//更改分润表中关于提现的审核的状态
			userBalanceMapper.updateUserBalanceStatus(orderNo, 2);//审核通过
		}
		
		switch (codeEnum) {
		case MERCHANT_UNLINE_ORDER:
			return merchantUnlineOrder(memberId, codeEnum, type, money,orderNo);
		case MERCHANT_STOCK:
			return merchantUnlineOrder(memberId, codeEnum, type, money,orderNo);
		case AGENT_STOCK:
			return merchantUnlineOrder(memberId, codeEnum, type, money,orderNo);
		case MERCHANT_WITHDRAWALS:
			return  merchantUnlineOrder(memberId, codeEnum, type, money,orderNo);
		case AGENT_WITHDRAWALS:
			return  merchantUnlineOrder(memberId, codeEnum, type, money,orderNo);
		default:
			throw new Exception("用户余额消费失败");
		}
	}

	/**
	 * 
	* @Title: merchantUnlineOrder
	* @Description: 使用余额支付
	* @author WQiang
	* @date  2017年3月29日 下午5:55:26
	* @param memberId
	* @param codeEnum
	* @param type
	* @param money
	* @return
	 */
	private int merchantUnlineOrder(long memberId, TransCodeEnum codeEnum, Integer type, long money,String orderNo) throws Exception {
		
		updateUserBalance(memberId, money);
		
		insertUserBalanceRecord(memberId, codeEnum.getCode(), type, money,orderNo);
		
		return Constants.SUCCESS;
	}
	
	/**
	 * 
	* @Title: updateUserBalance
	* @Description: 更新用户余额
	* @author WQiang
	* @date  2017年3月29日 下午6:20:21
	* @param memberId
	* @param money
	* @throws Exception
	 */
	@Transactional(rollbackFor=BizException.class)
	private void updateUserBalance(long memberId,long money) throws Exception {
		UserBalance userBalance = new UserBalance();
		userBalance.setManageId(memberId);
		UserBalance userBalance2 = merchantMapper.getUserBalance(userBalance);
		if(userBalance2.getBalance() < money){
			throw new Exception("余额不足");
		}
		userBalance.setBalance(userBalance2.getBalance() + money);
		if(merchantMapper.updateUserBalance(userBalance) != 1) {
			throw new Exception("更新用户余额失败");
		}
	}
	
	/**
	 * 
	* @Title: insertUserBalanceRecord
	* @Description: 插入余额流水
	* @author WQiang
	* @date  2017年3月29日 下午6:20:37
	 */
	private void insertUserBalanceRecord(long memberId, int transCode, Integer type, long money,String orderNo) throws Exception {
		UserBalanceRecord userBalanceRecord = new  UserBalanceRecord();
		userBalanceRecord.setMoney(money);
		userBalanceRecord.setTransCode(transCode);
		userBalanceRecord.setType(type);
		userBalanceRecord.setUserId(memberId);
		userBalanceRecord.setOrderNo(orderNo);
		if(merchantMapper.insertUserBalanceRecord(userBalanceRecord) !=1) {
			throw new Exception("更新用户余额失败");
		}
	}
    /**
     * 查询商户或者供应商或者代理商的余额
     */
    public Result getUserBalance(UserBalance userBalance){
  	  try {
	    	  UserBalance ub = merchantMapper.getUserBalance(userBalance);
	    	  if(ub == null){
	    		  return getResult(ResultEnum.NO_USER_BALANCE_RECORD_EXCEPTION);
	    	  }
	    	  return  getResult(ResultEnum.SUCCESS, ub);
  	  }catch (Exception e) {
 			logger.error("获取用户余额记录异常!");
 			e.printStackTrace();
 			return getResult(ResultEnum.USER_BALANCE_RECORD_EXCEPTION);
 		}
    };
    /**
	 * 更改商户提现状态
	 * @param orderNo
	 * @return
	 */
	public Result  updateMerchantWithdrawals(String orderNo,Integer status){
		Result result = getResult(ResultEnum.SUCCESS);
		if(userBalanceMapper.updateMerchantWithdrawals(orderNo, status) !=1){
			return getResult(ResultEnum.CASH_MERCHANT_EXCEPTION);
		}
		return result;
	} 
	/**
	 * 更改商户提现状态
	 * @param orderNo
	 * @return
	 */
	public Result  updateAgentWithdrawals(String orderNo,Integer status){
		Result result = getResult(ResultEnum.SUCCESS);
		if(userBalanceMapper.updateAgentWithdrawals(orderNo, status) !=1){
			return getResult(ResultEnum.CASH_AGENT_EXCEPTION);
		}
		return result;
	}
	/**
	 * 更改分润表中审核通过不通过的状态
	 * @param orderNo
	 * @param examineType
	 * @return
	 */
	public Result updateUserBalanceStatus(String orderNo,Integer status){
		Result result = getResult(ResultEnum.SUCCESS);
		if(userBalanceMapper.updateUserBalanceStatus(orderNo, status) != 1){
			return getResult(ResultEnum.CASH_USERPROFIT_EXCEPTION);
		}
		return result;
	}
}
